<?php

class UrLibraryController extends Controller
{
	

	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view','citylist','libraryselect','ajaxaddlib','addmylib'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('孟智'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new UrLibrary;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['UrLibrary']))
		{
			$model->attributes=$_POST['UrLibrary'];
			$model->province = $_POST['province'];
			$model->city = $_POST['city'];
			$model->create_datetime = time();
			$model->update_datetime = time();
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['UrLibrary']))
		{
			$model->attributes=$_POST['UrLibrary'];
			$model->province = $_POST['province'];
			$model->city = $_POST['city'];
			$model->update_datetime = time();
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'index' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('UrLibrary');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}
	
	

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new UrLibrary('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['UrLibrary']))
			$model->attributes=$_GET['UrLibrary'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=UrLibrary::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='ur-library-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	/**
	 * 根据省编码，获取市编码
	 */
	 public function actionCityList(){
		 $id = getPost('id');
		 $city = UrCity::model()->findAll('N_PROVID=?',array($id));
		 $html = '';
		 $html .= CHtml::dropDownList('city','',CHtml::listData($city,'N_CITYID','S_CITYNAME'));
		 echo $html;
		 }
		 
	/**
	 * 首页选择图书馆
	 * 生成floatlayout html代码
	 */
	 public function actionLibraryselect(){
		 if(user()->isGuest){
			 echo -1;exit;
			 }
		 $step = getPost('step');
		 $html = '';
		 if($step==1){
		 $html .= "<label for='province'>您目前所在地区：".SiteHelper::ajaxAreaSelect()."</label>";
		 $html .= "<br/><span style='float:right;'>".CHtml::button('下一步:从列表中选择图书馆',array('onclick'=>"
			$.ajax({
			url:'".$this->createUrl('/urLibrary/libraryselect')."',
			type:'POST',
			data:'step=2&provid='+$('#province').val()+'&cityid='+$('#city').val(),
			dataType:'html',
			success:function(data){
				$('#floatlayout_title').empty().append('第二步：从下面的列表中选择图书馆');
				$('#floatlayout_content').empty().append(data);
				}					
				});
		 "))."</span>";
		 echo $html;exit;
		 }elseif($step==2){
		   $provid = getPost('provid');
		   $cityid = getPost('cityid');
		   $province = UrProvince::model()->find('N_PROVID=:provid',array('provid'=>$provid));
		   $city = UrCity::model()->find('N_CITYID=:cityid',array('cityid'=>$cityid));
		   $libs = UrLibrary::model()->findAll('city=:city',array('city'=>$cityid));
		   $html .="您目前所在地区是:".$province->S_PROVNAME."&nbsp;&nbsp;".$city->S_CITYNAME;
		   $html .="<hr/>";
		   $html .=CHtml::beginForm($this->createUrl('/urLibrary/addmylib'),'post');
		   $html .= "<span id='liblists'>".CHtml::checkBoxList('libcheck','',CHtml::listData($libs,'id','name'))."</span>";
		   $html .= "<br/><span style='float:right;'>".CHtml::ajaxSubmitButton('完成','',array('type'=>'post','success'=>"function(data){alert(data)}"))."</span>";
		   $html .= CHtml::endForm();
		   $html .="<br/><hr/>".l('没找到我想要的图书馆','javascript:;',array('onclick'=>"$('#addnewlib').fadeIn();"))."<br/>";
		   $html .= "<span id='addnewlib' style='display:none'>".SiteHelper::ajaxAreaSelect()."&nbsp;&nbsp;".CHtml::textField('name','',array('id'=>'libname')).CHtml::button('添加',array('onclick'=>"if($('#libname').val()==''){alert('图书馆名称不能为空');return false;}else{
				$.ajax({
					url:'".$this->createUrl('/urLibrary/ajaxaddlib')."',
					type:'POST',
					dateType:'html',
					data:'provid='+$('#province').val()+'&cityid='+$('#city').val()+'&name='+$('#libname').val(),
					success:function(data){
						$('#liblists').empty().append(data);		
						}
					});
				}
		   "))."</span>";
		   echo $html;exit;
		 }
		 }
		 
		public function actionAjaxaddlib(){
			$html = '';
			$provid = getPost('provid');
			$cityid = getPost('cityid');
			$name = getPost('name');
			$model = new UrLibrary;
			$model->name = $name;
			$model->province = $provid;
			$model->city = $cityid;		
			$model->create_datetime = time();
			$model->update_datetime = time();
			if($model->save()){
		   $province = UrProvince::model()->find('N_PROVID=:provid',array('provid'=>$provid));
		   $city = UrCity::model()->find('N_CITYID=:cityid',array('cityid'=>$cityid));
		   $libs = UrLibrary::model()->findAll('city=:city',array('city'=>$cityid));
		   $html .= CHtml::checkBoxList('libcheck','',CHtml::listData($libs,'id','name'));
		   echo $html;exit;
			}
		}
		
		public function actionAddmylib(){
			$addtag = 0;
			$arrLib = getPost('libcheck');
			$arrLib = ($arrLib==null)?array():$arrLib;
			foreach($arrLib as $lib){
			$memberlib = new UrMemberLib;
			$memberlib->lid = $lib;
			$memberlib->uid = user()->id;
			$memberlib->create_datetime=time();
			$memberlib->update_datetime=time();	
			if($memberlib->save()){
				$addtag = 1;
				}		
			}
			if($addtag==1){
				sf('tips','图书馆数据添加成功！');
				}
			$this->redirect($this->createUrl('/'));
			}
}
